import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:deepseek_client/ai/service/chat_service.dart';
import 'package:deepseek_client/common/EventBus.dart';
import 'package:deepseek_client/common/SpConstants.dart';
import 'package:deepseek_client/common/constants/CancelConstants.dart';
import 'package:deepseek_client/common/controller/IAppController.dart';
import 'package:deepseek_client/common/db/ConversationWrapper.dart';
import 'package:deepseek_client/common/db/DbManager.dart';
import 'package:deepseek_client/common/event/event.dart';
import 'package:deepseek_client/common/utils/SpUtils.dart';
import 'package:deepseek_client/dto/StreamMessageDTO.dart';
import 'package:deepseek_client/extensions/StringExtensions.dart';
import 'package:deepseek_client/markdown/custom.dart';
import 'package:deepseek_client/markdown/latex.dart';
import 'package:deepseek_client/markdown/think.dart';
import 'package:deepseek_client/widget/KeepAliveWrapper.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:markdown_widget/markdown_widget.dart';
import 'package:deepseek_client/extensions/PlatformExtensions.dart';
import 'package:retrofit/retrofit.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:uuid/uuid.dart';
import '../common/bean/Message.dart';

class HomePage extends StatefulWidget {
  final IAppController parentController;
  final double screenWidth;
  final IChatService? service;

  const HomePage(
      {super.key, required this.parentController, required this.screenWidth, required this.service});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  final TextEditingController _controller = TextEditingController();
  final ValueNotifier<List<Message>> _msgNotifier = ValueNotifier([]);
  final ValueNotifier<bool> _showStopButtonNotifier = ValueNotifier(false);
  final ValueNotifier<bool> _showThinkNotifier = ValueNotifier(false);
  final ScrollController _listController = ScrollController();
  final FocusNode _inputFocusNode = FocusNode();
  late AnimationController _dragonController;
  late Animation<double> _dragonAnimation;

  //当前会话
  ConversationWrapper? _curConversation;

  // String? lastRequestId;

  int responseTapTime = 0;

  CancelToken? _msgRequestCancelToken;

  StreamSubscription? _conversationUpdateTask;
  StreamSubscription? _historyClearTask;
  StreamSubscription? _clearFocusTask;
  StreamSubscription? _recoveryFocusTask;

  @override
  void initState() {
    super.initState();
    checkHasEmptyConversation();
    initAnimation();
    _conversationUpdateTask =
        eventBus.on<OnHistoryItemTapEvent>().listen((event) {
      _curConversation = event.conversation;
      String jsonStr = event.conversation.conversationListJson;
      // _msgNotifier.value = json.decode(jsonStr);
      List<dynamic> list = json.decode(jsonStr);
      List<Message> msgList = [];
      for (var msgDynamic in list) {
        Message msg = Message.fromJson(msgDynamic);
        msgList.add(msg);
      }
      _msgNotifier.value = msgList;
      _scrollToBottom();
    });
    _historyClearTask = eventBus.on<HistoryClearEvent>().listen((event) async {
      if (_curConversation?.conversationListJson == "") {
        return;
      }
      _reset();
    });
    _clearFocusTask = eventBus.on<OnModelSelectTapEvent>().listen((event) {
      _inputFocusNode.unfocus();
    });
    _recoveryFocusTask = eventBus.on<RequestFocusEvent>().listen((event) {
      _inputFocusNode.requestFocus();
    });
    Timer(const Duration(milliseconds: 500), () {
      _inputFocusNode.requestFocus();
    });
  }

  initAnimation() {
    _dragonController = AnimationController(
      duration: const Duration(milliseconds: 20000),
      vsync: this,
    );
    _dragonAnimation =
        Tween<double>(begin: 0, end: -1).animate(_dragonController);
    _dragonController.repeat();
  }

  checkHasEmptyConversation() async {
    var conversations =
        await database?.conversationDao.findAllConversation() ?? [];
    for (var conversation in conversations) {
      if (conversation.conversationListJson == "") {
        database?.conversationDao.delete(conversation.id ?? "0");
      }
    }

    _reset();
  }

  _reset() {
    widget.parentController.setTitle("新会话");
    _msgRequestCancelToken?.cancel(CancelReasons.START_NEW_CONVERSATION);
    _msgNotifier.value = [];
    DateFormat dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
    _curConversation = ConversationWrapper(
        id: const Uuid().v4(),
        title: "",
        conversationListJson: "",
        createTime: dateFormat.format(DateTime.now()));
  }

  @override
  void dispose() {
    _recoveryFocusTask?.cancel();
    _clearFocusTask?.cancel();
    _historyClearTask?.cancel();
    _conversationUpdateTask?.cancel();
    _dragonController.dispose();
    _showStopButtonNotifier.dispose();
    _inputFocusNode.dispose();
    _controller.dispose();
    _msgNotifier.dispose();
    _listController.dispose();
    super.dispose();
  }

  ///滚动到底部
  void _scrollToBottom() {
    if (_listController.hasClients) {
      _listController.animateTo(
        _listController.position.maxScrollExtent, // 滚动到最低部
        duration: const Duration(milliseconds: 300), // 动画时长
        curve: Curves.easeOut, // 动画曲线
      );
    }
  }

  ///按下回车的一瞬间执行这个方法
  void _onTextSubmitted(String value) async {
    var currentModel =
        await SpUtils.getInstance().getString(SpConstants.model) ?? "";
    if (currentModel.isEmpty) {
      TDToast.showText("模型为空", context: context);
      return;
    }
    _controller.clear();
    String requestId = await insertSendMsg(value);
    await Future.delayed(const Duration(milliseconds: 300));
    insertLndicatorMsg(requestId);
    var lastList = List<Message>.from(_msgNotifier.value ?? []);
    // lastList.add(Message(role: "user", content: value));
    List<Message> mMsgList = List<Message>.from(lastList);
    mMsgList.removeWhere((msg) {
      return msg.role == "loading";
    });
    if (_msgRequestCancelToken != null) {
      _msgRequestCancelToken?.cancel(CancelReasons.STOP_LAST_WHEN_INSERT_NEW);
    }
    _msgRequestCancelToken = CancelToken();
    var request = {
      "model": currentModel,
      "messages": mMsgList,
      "options": {"temperature": 0.8, "num_predict": -1},
      // "stream": false
    };
    // _showStopButtonNotifier.value = true;
    // client?.chat(_msgRequestCancelToken!, json.encode(request)).then((res) {
    //   //结果：res.response
    //   insertResponseMsg(res.message?.content ?? "");
    //   _showStopButtonNotifier.value = false;
    // }).catchError((err, stack) {
    //   _showStopButtonNotifier.value = false;
    //   if (err is DioException && err.type == DioExceptionType.cancel) {
    //     insertResponseMsg("用户已终止当前回复");
    //   } else {
    //     insertResponseMsg(err.message ?? "");
    //   }
    // });
    try {
      // RestClient streamClient =
      //     RestClient(DioUtils.getInstance().getStreamDio());
      //显示停止按钮
      _showStopButtonNotifier.value = true;
      var res = await widget.service?.chatStream(request , _msgRequestCancelToken);
      Stream<Uint8List> stream = ((res as HttpResponse?)?.data as ResponseBody).stream;
      StringBuffer thinkBuffer = StringBuffer();
      StringBuffer chatBuffer = StringBuffer();
      await for (var data in stream) {
        // 将字节数据解码为字符串
        final bytes = data as List<int>;
        final decodedData = utf8.decode(bytes);
        StreamMessageDto msg =
            StreamMessageDto.fromJson(json.decode(decodedData));
        var content = msg.message?.content ?? "";
        print(content);
        // if (content.contains('<think>')) {
        //   //思考开始
        //   _showThinkNotifier.value = true;
        // } else if (content.contains('</think>')) {
        //   _showThinkNotifier.value = false;
        // }
        // if (!_showThinkNotifier.value) {
        chatBuffer.write(content);
        // } else {
        //   thinkBuffer.write(content);
        // }
        insertStreamResponseMsg(
            !_showThinkNotifier.value ? thinkBuffer.toString() : null,
            chatBuffer.toString(),
            requestId: requestId);
      }
      _showStopButtonNotifier.value = false;
    } catch (e) {
      if (e is DioException) {
        if (e.error == CancelReasons.CANCEL_SYSTEM_RESPONSE) {
          // insertStreamResponseMsg("", "用户已终止当前回复", requestId: requestId);
        } else if (e.error == CancelReasons.START_NEW_CONVERSATION) {
        } else if (e.error == CancelReasons.STOP_LAST_WHEN_INSERT_NEW) {
        } else {
          insertResponseMsg(e.message ?? "");
        }
      }
      _showStopButtonNotifier.value = false;
    }
  }

  /// 插入发送消息
  insertSendMsg(String msg) async {
    String requestId = const Uuid().v4();
    var newData = List<Message>.from(_msgNotifier.value ?? []);
    if (newData.isEmpty) {
      _curConversation?.title = msg;
      widget.parentController.setTitle(msg);
    }
    for (var message in newData) {
      message.displayComplete = true;
    }
    newData.add(Message(content: msg, id: requestId, role: "user"));
    _msgNotifier.value = newData;
    _curConversation?.conversationListJson = json.encode(newData);
    if (_curConversation != null) {
      var cacheConversation = await database?.conversationDao
          .findConversationById(_curConversation?.id ?? "");
      if (cacheConversation == null) {
        database?.conversationDao.insertConversation(_curConversation!);
      } else {
        database?.conversationDao.updateConversation(_curConversation!);
      }
    }

    eventBus.fire(UpdateConversationHistoryEvent());
    _sendComplete();
    return requestId;
  }

  void insertLndicatorMsg(String requestId) {
    var oldData = List<Message>.from(_msgNotifier.value ?? []);
    oldData.add(Message(role: "loading", content: "", id: requestId));
    _msgNotifier.value = oldData;
    _sendComplete();
  }

  /// 插入大模型回复的消息
  insertResponseMsg(String res) async {
    var oldData = List<Message>.from(_msgNotifier.value ?? []);
    oldData.removeWhere((message) {
      return message.role == "loading";
    });
    oldData.add(Message(role: "assistant", content: res));
    _curConversation?.conversationListJson = json.encode(oldData);
    await database?.conversationDao.updateConversation(_curConversation!);
    eventBus.fire(UpdateConversationHistoryEvent());
    _msgNotifier.value = oldData;
  }

  /// 插入大模型回复的消息，以及出错时系统自动插入的消息
  insertStreamResponseMsg(String? think, String content,
      {required String requestId}) async {
    var oldData = List<Message>.from(_msgNotifier.value ?? []);
    int index = -1;
    // int thinkingIndex = -1;
    for (var msg in oldData) {
      if (msg.id == requestId && msg.role == "assistant") {
        index = oldData.indexOf(msg);
        break;
      }
      // if (msg.role == "thinking" && msg.id == requestId) {
      //   thinkingIndex = oldData.indexOf(msg);
      //   break;
      // }
    }
    oldData.removeWhere((message) {
      return message.role == "loading";
    });
    // think = think ?? "";
    //没有就插入，有就更新
    // if (think == null) {
    // if (_showThinkNotifier.value) {
    //   if (thinkingIndex == -1) {
    //     oldData.add(Message(role: "thinking", content: null, id: requestId));
    //   } else {
    //     oldData[thinkingIndex].content = null;
    //   }
    // } else {
    //   oldData.removeWhere((message) {
    //     return message.role == "thinking" && message.id == requestId;
    //   });
    // }
    // } else {
    // oldData.removeWhere((message) {
    //   return message.role == "thinking" && message.id == requestId;
    // });
    if (index == -1) {
      oldData.add(
          Message(role: "assistant", content: "$think$content", id: requestId));
    } else {
      oldData[index].content = "$think$content";
    }
    // }
    _curConversation?.conversationListJson = json.encode(oldData);
    _msgNotifier.value = oldData;
    await database?.conversationDao.updateConversation(_curConversation!);
    eventBus.fire(UpdateConversationHistoryEvent());
    // _sendComplete();
  }

  /// 发送完成，滚动到底部，并获取焦点
  _sendComplete() async {
    await Future.delayed(const Duration(milliseconds: 300));
    _scrollToBottom();
    if (isNotPhone) {
      _inputFocusNode.requestFocus();
    }
  }

  ///对markdown中的<think>标签进行预处理，去除特殊字符
  _preHandleMarkdown(String markdownData) {
    // 定义<think>和</think>标签的正则表达式
    RegExp thinkRegex =
        RegExp(r'<think>(.*?)</think>', multiLine: true, dotAll: true);
    if (thinkRegex.hasMatch(markdownData)) {
      // 查找匹配的<think>标签
      Match? match = thinkRegex.firstMatch(markdownData);
      // 如果找到匹配项，则提取<think>和</think>之间的文本
      String thinkContent = match?.group(1) ?? "";
      StringBuffer sb = StringBuffer();
      for (var char in thinkContent.split('')) {
        bool isValid = char.isChinese() ||
            char.isLetter() ||
            char.isPunctuation() ||
            char.isDigit();
        if (isValid) {
          break;
        }
        sb.write(char);
      }
      String newThink = thinkContent.replaceAll(sb.toString(), "");
      if (newThink.isEmpty) {
        return markdownData.replaceAll('<think>$thinkContent</think>', '');
      }
      return markdownData.replaceAll(
          '<think>$thinkContent</think>', '<think>$newThink</think>');
    } else {
      return markdownData;
    }
  }

  void _onEnterPress(String value) async {
    if (value.isEmpty) {
      TDToast.showText("不能发送空内容", context: context);
      return;
    }
    _onTextSubmitted(value);
  }

  @override
  Widget build(BuildContext context) {
    getContextMenu(context, editableTextState) {
      return AdaptiveTextSelectionToolbar.buttonItems(buttonItems: [
        ContextMenuButtonItem(
          onPressed: () {
            // 如果有选中文本，则复制选中的文本，否则复制整个文本
            if (editableTextState.textEditingValue.selection.isValid &&
                !editableTextState.textEditingValue.selection.isCollapsed) {
              editableTextState.copySelection(SelectionChangedCause.toolbar);
            } else {
              // 复制整个文本
              Clipboard.setData(
                  ClipboardData(text: editableTextState.textEditingValue.text));
              editableTextState.hideToolbar();
            }
          },
          label: '复制',
        ),
        ContextMenuButtonItem(
          onPressed: () {
            editableTextState.selectAll(SelectionChangedCause.doubleTap);
            editableTextState.hideToolbar();
          },
          label: '全选',
        ),
      ], anchors: editableTextState.contextMenuAnchors);
    }

    TextStyle responseStyle = const TextStyle(
        color: Colors.black, fontSize: 16, decoration: TextDecoration.none);

    TextStyle requestStyle = const TextStyle(
        color: Color(0xFFFFFFFF),
        fontSize: 16,
        decoration: TextDecoration.none);

    getInputWidget() {
      return CallbackShortcuts(
          bindings: {
            const SingleActivator(LogicalKeyboardKey.enter, control: true): () {
              //换行
              _controller.text += "\n";
            },
            const SingleActivator(LogicalKeyboardKey.enter, control: false):
                () {
              _onEnterPress(_controller.text);
            }
          },
          child: Focus(
              child: Container(
            width: double.infinity,
            height: 100,
            alignment: AlignmentDirectional.topCenter,
            decoration: BoxDecoration(
                color: const Color(0x88E1E1E1),
                border: Border.all(color: const Color(0xFFCDCCCC), width: 1.0),
                borderRadius: BorderRadius.circular(16)),
            padding:
                const EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),
            margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
            child: TextField(
              expands: true,
              focusNode: _inputFocusNode,
              controller: _controller,
              maxLines: null,
              keyboardType: TextInputType.text,
              textInputAction: TextInputAction.send,
              style: requestStyle.copyWith(color: const Color(0xFF141414)),
              onSubmitted: _onEnterPress,
              decoration: const InputDecoration(
                  hintText: "请输入要询问的内容",
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                  hintStyle: TextStyle(
                    color: Color(0xFF6A6A6A),
                  )),
            ),
          )));
    }

    getListItemWidget(Message item) {
      if (item.role == "assistant") {
        return LayoutBuilder(builder: (context, constraints) {
          var containerWidth = constraints.widthConstraints().maxWidth;
          return Align(
            alignment: AlignmentDirectional.centerStart,
            child: Container(
              constraints: BoxConstraints(
                  maxWidth: containerWidth / 4 * 3,
                  minWidth: containerWidth / 4),
              margin: const EdgeInsets.only(left: 20, top: 20, bottom: 10),
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: const Color(0xFFFFFFFF),
                borderRadius: BorderRadius.circular(16),
                boxShadow: const [
                  BoxShadow(
                    color: Color(0xAA999999),
                    offset: Offset(0, 0),
                    blurRadius: 5,
                    spreadRadius: 0,
                  )
                ],
              ),
              // child: ResponseWidget(text: item.content ?? "" , needType: _msgNotifier.value.lastOrNull == item && !item.displayComplete,),
              child: Padding(
                padding: const EdgeInsets.all(10),
                child: MarkdownWidget(
                  // data: _isMarkdown(item.content ?? "") ? _preHandleMarkdown(item.content ?? "") : TypewriterText(
                  data: _preHandleMarkdown(item.content ?? ""),
                  // data: item.content ?? "",
                  selectable: true,
                  shrinkWrap: true,
                  config: MarkdownConfig(configs: [
                    const PConfig(
                        textStyle: TextStyle(
                            color: Color(0xFF6C6C6C),
                            fontSize: 16,
                            fontWeight: FontWeight.w500))
                  ]),
                  markdownGenerator: MarkdownGenerator(
                    inlineSyntaxList: [LatexSyntax()],
                    generators: [
                      SpanNodeGeneratorWithTag(
                          tag: 'think',
                          generator: (e, config, visitor) {
                            return ThinkNode(visitor, element: e,
                                onComplete: () {
                              item.displayComplete = true;
                            }, onLineBreak: () async {});
                          }),
                      latexGenerator
                    ],
                    textGenerator: (e, config, visitor) {
                      return CustomTextNode(
                        item,
                        e.textContent,
                        config,
                        visitor,
                      );
                    },
                  ),
                ),
              ),
            ),
          );
        });
      }
      // else if (item.role == "thinking") {
      //   var maxWidth = widget.screenWidth / 4 * 3;
      //   return Align(
      //     alignment: AlignmentDirectional.centerStart,
      //     child: Container(
      //       constraints: BoxConstraints(
      //           maxWidth: maxWidth,
      //           minWidth: maxWidth > 300 ? 300 : maxWidth,
      //           maxHeight: 50),
      //       margin: const EdgeInsets.only(left: 20, top: 20, bottom: 10),
      //       padding: const EdgeInsets.all(10),
      //       decoration: BoxDecoration(
      //         color: const Color(0xFFFFFFFF),
      //         borderRadius: BorderRadius.circular(16),
      //         boxShadow: const [
      //           BoxShadow(
      //             color: Color(0xAA999999),
      //             offset: Offset(0, 0),
      //             blurRadius: 5,
      //             spreadRadius: 0,
      //           )
      //         ],
      //       ),
      //       child: const SizedBox(
      //         width: 20,
      //         child: Center(
      //           child: Row(
      //             mainAxisSize: MainAxisSize.min,
      //             crossAxisAlignment: CrossAxisAlignment.center,
      //             children: [
      //               Text(
      //                 "深度思考中",
      //                 style: TextStyle(color: Colors.black),
      //               ),
      //               SizedBox(
      //                 width: 10,
      //               ),
      //               LoadingIndicator(
      //                   indicatorType: Indicator.ballSpinFadeLoader,
      //                   colors: [Colors.grey],
      //                   strokeWidth: 1)
      //             ],
      //           ),
      //         ),
      //       ),
      //     ),
      //   );
      // }
      else if (item.role == "loading") {
        var maxWidth = widget.screenWidth / 4 * 3;
        return Align(
          alignment: AlignmentDirectional.centerStart,
          child: Container(
            constraints: BoxConstraints(
                maxWidth: maxWidth,
                minWidth: maxWidth > 300 ? 300 : maxWidth,
                maxHeight: 50,
                minHeight: 50),
            margin: const EdgeInsets.only(left: 20, top: 20, bottom: 10),
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: const Color(0xFFFFFFFF),
              borderRadius: BorderRadius.circular(16),
              boxShadow: const [
                BoxShadow(
                  color: Color(0xAA999999),
                  offset: Offset(0, 0),
                  blurRadius: 5,
                  spreadRadius: 0,
                )
              ],
            ),
            child: const SizedBox(
              width: 20,
              child: Center(
                child: LoadingIndicator(
                    indicatorType: Indicator.lineScale,

                    /// Required, The loading type of the widget
                    colors: [Colors.grey],

                    /// Optional, The color collections
                    strokeWidth: 2

                    /// Optional, the stroke backgroundColor
                    ),
              ),
            ),
          ),
        );
      } else {
        return Align(
          alignment: AlignmentDirectional.centerEnd,
          child: Container(
            padding: const EdgeInsets.all(10),
            constraints: BoxConstraints(
              maxWidth: widget.screenWidth / 4 * 3,
            ),
            margin: const EdgeInsets.only(right: 20, top: 20, bottom: 10),
            decoration: BoxDecoration(
              color: const Color(0xDDFF5D33),
              borderRadius: BorderRadius.circular(16),
              boxShadow: const [
                BoxShadow(
                  color: Color(0xAA999999),
                  offset: Offset(0, 0),
                  blurRadius: 3,
                  spreadRadius: 0,
                )
              ],
            ),
            child: SelectableText(
              item.content ?? "",
              style: item.role == "assistant" ? responseStyle : requestStyle,
              contextMenuBuilder: (context, editableTextState) {
                return getContextMenu(context, editableTextState);
              },
            ),
          ),
        );
      }
    }

    getListWidget() {
      var containerWidth = MediaQuery.of(context).size.width;
      return Container(
        width: double.infinity,
        height: double.infinity,
        child: ValueListenableBuilder(
            valueListenable: _msgNotifier,
            builder: (context, list, child) {
              if (list.isEmpty) {
                return Container(
                  alignment: AlignmentDirectional.center,
                  child: AnimatedBuilder(
                      animation: _dragonAnimation,
                      builder: (context, child) {
                        return Transform.rotate(
                          angle: _dragonAnimation.value * 2 * pi,
                          child: isPhone
                              ? Image.asset(
                                  'assets/fire_dragon.png',
                                  width: containerWidth * 0.8,
                                )
                              : Image.asset(
                                  'assets/fire_dragon.png',
                                  height: 200,
                                ),
                        );
                      }),
                );
              }
              return ListView.builder(
                itemBuilder: (context, index) {
                  var item = list[index];
                  return KeepAliveWrapper(
                      child: SizedBox(
                    width: double.infinity,
                    child: getListItemWidget(item),
                  ));
                },
                shrinkWrap: false,
                itemCount: list.length,
                controller: _listController,
              );
            }),
      );
    }

    return GestureDetector(
      onTap: () async {
        eventBus.fire(CollapseHistoryEvent());
      },
      child: Container(
        width: widget.screenWidth,
        height: double.infinity,
        color: Colors.white,
        padding: isNotPhone
            ? const EdgeInsets.only(top: 60)
            : const EdgeInsets.only(top: 0),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Expanded(child: getListWidget()),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MouseRegion(
                  cursor: SystemMouseCursors.click,
                  child: GestureDetector(
                    onTap: () async {
                      if (_curConversation?.conversationListJson == "") {
                        return;
                      }
                      _reset();
                    },
                    child: Container(
                      width: 100,
                      height: 28,
                      alignment: AlignmentDirectional.center,
                      margin: const EdgeInsets.only(top: 10),
                      decoration: BoxDecoration(
                          border: Border.all(
                              color: const Color(0xFFBFBFBF), width: 1.0),
                          borderRadius: BorderRadius.circular(14)),
                      child: Row(mainAxisSize: MainAxisSize.min, children: [
                        Image.asset(
                          "assets/new_chat.png",
                          width: 16,
                          height: 16,
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        const Text(
                          "开启新会话",
                          style: TextStyle(
                            color: Color(0xFF141414),
                            fontSize: 12,
                          ),
                        )
                      ]),
                    ),
                  ),
                ),
                ValueListenableBuilder(
                    valueListenable: _showStopButtonNotifier,
                    builder: (context, show, child) {
                      if (!show) {
                        return const SizedBox();
                      }
                      return MouseRegion(
                        cursor: SystemMouseCursors.click,
                        child: GestureDetector(
                          onTap: () async {
                            _msgRequestCancelToken
                                ?.cancel(CancelReasons.CANCEL_SYSTEM_RESPONSE);
                            _showStopButtonNotifier.value = false;
                            _showThinkNotifier.value = false;
                          },
                          child: Container(
                            width: 100,
                            height: 28,
                            margin: const EdgeInsets.only(left: 10, top: 10),
                            alignment: AlignmentDirectional.center,
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: const Color(0xFFBFBFBF), width: 1.0),
                                borderRadius: BorderRadius.circular(14)),
                            child: const Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.pause_circle,
                                    size: 16,
                                    color: Color(0xFF686868),
                                  ),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Text(
                                    "停止",
                                    style: TextStyle(
                                      color: Color(0xFF141414),
                                      fontSize: 12,
                                    ),
                                  )
                                ]),
                          ),
                        ),
                      );
                    })
              ],
            ),
            getInputWidget(),
            const SizedBox(
              height: 10,
            )
          ],
        ),
      ),
    );
  }
}
